﻿using Cl.Model.Results;
using Cl.Utils;
using Cl.Utils.Helper;
using Cl.Utils.Primitives.Class.UploadFile;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cl.Service.Service.System.UploadFile
{
    public class FileService : IFileService
    {
        // 注：Env 是 IWebHostEnvironment 实例，通常通过构造函数注入
        // 如果您还没有添加，可以这样修改构造函数：
        private readonly IWebHostEnvironment Env;

        private readonly IHttpContextAccessor? HttpContextAccessor;

        private string MainPath;
        private string Ip;

        /// <summary>
        /// 构造函数
        /// </summary>
        public FileService(IWebHostEnvironment env, IHttpContextAccessor httpContextAccessor)
        {
            Env = env;
            HttpContextAccessor = httpContextAccessor;

            MainPath = Env.ContentRootPath;

            var request = HttpContextAccessor?.HttpContext?.Request;
            string serverIpAddress = request?.Host.Host ?? ""; // 获取主机名，默认情况下应该是服务器的IP地址或域名
            int? serverPort = request?.Host.Port; // 获取端口号


            Ip = $"{serverIpAddress}:{serverPort}";
        }


        public ResultInfoModel Delete(UploadType uploadType, string id)
        {
            UploadFileHelper.DeleteFile(uploadType, id);
            return GetResult.Success();
        }

        public ResultInfoModel DeleteByFileName(UploadType uploadType, string id, string fileName)
        {
            UploadFileHelper.DeleteByFileName(uploadType, id, fileName);
            return GetResult.Success();
        }


        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file">文件资源</param>
        /// <param name="uploadType">上传类型</param>
        /// <param name="id"></param>
        /// <param name="multipleFile">是否是多文件</param>
        /// <returns></returns>
        public async Task<ResultInfoModel> UploadFileAsync(IFormFile file, UploadType uploadType, string id, bool multipleFile = false)
        {
            if (file == null)
                return GetResult.Error("参数空");
            //文件的扩展名
            var extention = Path.GetExtension(file.FileName).ToLower();
            var hasIncludeExtension = GlobalService.FileConfigGlobal.IncludeExtension.Count > 0;
            if (hasIncludeExtension && !GlobalService.FileConfigGlobal.IncludeExtension.Contains(extention))
            {
                return GetResult.Error("不是白名单");
            }

            var hasExcludeExtension = GlobalService.FileConfigGlobal.ExcludeExtension.Count > 0;
            if (hasExcludeExtension && GlobalService.FileConfigGlobal.ExcludeExtension.Contains(extention))
            {
                return GetResult.Error("在黑名单");
            }
            var fileLenth = file.Length;
            if (fileLenth > GlobalService.FileConfigGlobal.MaxSize)
            {
                return GetResult.Error("超过最大限制");
            }


            if (file == null || file.Length == 0)
            {
                return GetResult.Error("文件是空");
            }

            //如果是单文件，则删除旧文件；
            if (!multipleFile)
                Delete(uploadType, id);

            string FolderPath = await UploadFileHelper.UploadFileAsync(file, uploadType, id);

            // 构造并返回图片的URL
            //return GetResult.Success($"{Ip}/{FolderPath}/{file.FileName}");
            return GetResult.Success($"/{FolderPath}");
        }



        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="uploadType"></param>
        /// <param name="file"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public List<string> GetFileList(UploadType uploadType, string id)
        {
            //List<string> result = new List<string>();
            var result = UploadFileHelper.GetUploadsPathList(uploadType, id);
            //string FolderPath = await UploadFileHelper.UploadFileAsync(file, uploadType, id);

            //// 构造并返回图片的URL
            ////return GetResult.Success($"{Ip}/{FolderPath}/{file.FileName}");
            //return GetResult.Success($"/{FolderPath}/{file.FileName}");
            return result;
        }

    }
}
